package com.changgou.gateway.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class JwtUtil {

    public static String publickey
            = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA10CtXJLMtkFmPUNkRNQK7smqMGTm+O29WR8JaWrOksGYmImiaCVg1fo7yIbyKiukl+uBl9t4F9POkGPOeilWuNfz8QhAdQ1CoAVUISIsvn2oJL8+x/3My4kHHtZKJsRuIJilfnyiVRdkTEs2wSDipOFxczEIyM1tWR1Odbepax0j6Jxvg38mzqoMViFfHhtuh0h5U659wIgRGXlJuGuBpVbIbp7CO+/DuQR0M/dX4GnwS4TXXUqCJ651zz28ERuEtVRjO3FIqc1U4kvtMEsPMdpTCsawj2cfv9Zj3EfVOK3thAOMsjJVukOWwejOIw5qfdbHMgun6XB5aORcbplHawIDAQAB-----END PUBLIC KEY-----";
/*
    //有效期为
    public static final Long JWT_TTL = 3600000L;// 60 * 60 *1000  一个小时

    //Jwt令牌信息
    public static final String JWT_KEY = "piaopiaoguangchang";

    public static String createJWT(String id, String subject, Long ttlMillis) {
        //指定算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        //当前系统时间
        long nowMillis = System.currentTimeMillis();
        //令牌签发时间
        Date now = new Date(nowMillis);

        //如果令牌有效期为null，则默认设置有效期1小时
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }

        //令牌过期时间设置
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);

        //生成秘钥
        SecretKey secretKey = generalKey();

        //封装Jwt令牌信息
        JwtBuilder builder = Jwts.builder()
                .setId(id)                    //唯一的ID
                .setSubject(subject)          // 主题  可以是JSON数据
                .setIssuer("admin")          // 签发者
                .setIssuedAt(now)             // 签发时间
                .signWith(signatureAlgorithm, secretKey) // 签名算法以及密匙
                .setExpiration(expDate);      // 设置过期时间
        return builder.compact();
    }

    *//**
     * 生成加密 secretKey
     *//*
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getEncoder().encode(JwtUtil.JWT_KEY.getBytes());
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }


    *//**
     * 解析令牌数据
     *//*
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }*/
}